<template>
  <div class="profile-container">
    <div class="profile-header">
      <h2 class="page-title">个人信息</h2>
      <el-button 
        v-if="!isEditing"
        type="primary" 
        @click="startEditing"
        class="edit-btn"
      >
        <el-icon><Edit /></el-icon>
        编辑资料
      </el-button>
    </div>
    
    <el-form 
      ref="profileFormRef" 
      :model="profileForm" 
      :rules="profileRules" 
      class="profile-form"
      :disabled="!isEditing"
    >
      <!-- 头像上传 -->
      <el-form-item label="头像">
        <div class="avatar-uploader">
          <el-upload
            class="avatar-upload"
            :show-file-list="false"
            action="#"
            :before-upload="beforeUploadAvatar"
            :disabled="!isEditing"
            accept="image/*"
          >
            <img v-if="profileForm.avatar" :src="profileForm.avatar" class="avatar">
            <i v-else class="el-icon-plus avatar-uploader-icon"></i>
          </el-upload>
          <p class="avatar-tip">支持JPG、PNG格式，文件大小不超过2MB</p>
        </div>
      </el-form-item>
      
      <!-- 基本信息 -->
      <div class="form-section">
        <h3 class="section-title">基本信息</h3>
        
        <el-form-item label="昵称" prop="nickname">
          <el-input 
            v-model="profileForm.nickname" 
            placeholder="请输入昵称"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="真实姓名" prop="realName">
          <el-input 
            v-model="profileForm.realName" 
            placeholder="请输入真实姓名"
            clearable
          />
        </el-form-item>
        
        <el-form-item label="性别" prop="gender">
          <el-radio-group v-model="profileForm.gender">
            <el-radio label="male">男</el-radio>
            <el-radio label="female">女</el-radio>
            <el-radio label="other">其他</el-radio>
          </el-radio-group>
        </el-form-item>
        
        <el-form-item label="生日" prop="birthday">
          <el-date-picker
            v-model="profileForm.birthday"
            type="date"
            placeholder="请选择生日"
            format="YYYY-MM-DD"
            value-format="YYYY-MM-DD"
            :disabled-date="(time) => time.getTime() > Date.now()"
          />
        </el-form-item>
        
        <el-form-item label="手机号">
          <el-input 
            v-model="profileForm.phone" 
            placeholder="请输入手机号"
            disabled
          />
          <el-link type="primary" @click="goToModifyPhone" class="modify-link">修改</el-link>
        </el-form-item>
        
        <el-form-item label="邮箱" prop="email">
          <el-input 
            v-model="profileForm.email" 
            type="email"
            placeholder="请输入邮箱"
            clearable
          />
        </el-form-item>
      </div>
      
      <!-- 联系信息 -->
      <div class="form-section">
        <h3 class="section-title">联系信息</h3>
        
        <el-form-item label="所在地区" prop="region">
          <el-cascader
            v-model="profileForm.region"
            :options="regionOptions"
            placeholder="请选择省/市/区"
            style="width: 100%;"
          />
        </el-form-item>
        
        <el-form-item label="详细地址" prop="address">
          <el-input 
            v-model="profileForm.address" 
            placeholder="请输入详细地址"
            type="textarea"
            :rows="2"
          />
        </el-form-item>
        
        <el-form-item label="邮政编码" prop="zipCode">
          <el-input 
            v-model="profileForm.zipCode" 
            placeholder="请输入邮政编码"
            maxlength="6"
            show-word-limit
          />
        </el-form-item>
      </div>
      
      <!-- 账号安全 -->
      <div class="form-section">
        <h3 class="section-title">账号安全</h3>
        
        <el-form-item label="登录密码">
          <el-input 
            type="password"
            placeholder="******"
            disabled
          />
          <el-link type="primary" @click="goToModifyPassword" class="modify-link">修改</el-link>
        </el-form-item>
        
        <el-form-item label="支付密码">
          <el-input 
            type="password"
            placeholder="未设置"
            disabled
          />
          <el-link type="primary" @click="goToSetPayPassword" class="modify-link">设置</el-link>
        </el-form-item>
      </div>
      
      <!-- 操作按钮 -->
      <el-form-item v-if="isEditing">
        <el-button 
          type="primary" 
          @click="handleSave"
          :loading="saving"
          class="save-btn"
        >
          保存
        </el-button>
        <el-button @click="cancelEditing" class="cancel-btn">
          取消
        </el-button>
      </el-form-item>
    </el-form>
  </div>
</template>

<script setup>
import { ref, reactive, computed } from 'vue'
import { useRouter } from 'vue-router'
import { useUserStore } from '../../store/modules/user'
import { Edit } from '@element-plus/icons-vue'
import { ElMessage } from 'element-plus'

const router = useRouter()
const userStore = useUserStore()
const profileFormRef = ref(null)
const isEditing = ref(false)
const saving = ref(false)

// 备份原始数据，用于取消编辑
let originalFormData = null

// 表单数据
const profileForm = reactive({
  nickname: 'AI商城用户',
  realName: '',
  gender: '',
  birthday: '',
  phone: '138****8000',
  email: '',
  avatar: '/assets/default-avatar.png',
  region: [],
  address: '',
  zipCode: ''
})

// 表单验证规则
const profileRules = {
  nickname: [
    { required: true, message: '请输入昵称', trigger: 'blur' },
    { min: 2, max: 20, message: '昵称长度在2-20个字符之间', trigger: 'blur' }
  ],
  realName: [
    { required: true, message: '请输入真实姓名', trigger: 'blur' },
    { min: 2, max: 20, message: '真实姓名长度在2-20个字符之间', trigger: 'blur' }
  ],
  email: [
    { type: 'email', message: '请输入正确的邮箱地址', trigger: 'blur' }
  ],
  region: [
    { required: true, message: '请选择所在地区', trigger: 'change' }
  ],
  address: [
    { required: true, message: '请输入详细地址', trigger: 'blur' },
    { min: 5, message: '详细地址至少5个字符', trigger: 'blur' }
  ],
  zipCode: [
    { pattern: /^\d{6}$/, message: '邮政编码为6位数字', trigger: 'blur' }
  ]
}

// 地区选项（模拟数据）
const regionOptions = [
  {
    value: 'beijing',
    label: '北京市',
    children: [
      {
        value: 'chaoyang',
        label: '朝阳区',
        children: [
          { value: 'cbd', label: 'CBD' },
          { value: 'sanyuanqiao', label: '三元桥' }
        ]
      },
      {
        value: 'haidian',
        label: '海淀区',
        children: [
          { value: 'zhongguancun', label: '中关村' },
          { value: 'wudaokou', label: '五道口' }
        ]
      }
    ]
  },
  {
    value: 'shanghai',
    label: '上海市',
    children: [
      {
        value: 'pudong',
        label: '浦东新区',
        children: [
          { value: 'lujiazui', label: '陆家嘴' },
          { value: 'zhangjiang', label: '张江' }
        ]
      },
      {
        value: 'xuhui',
        label: '徐汇区',
        children: [
          { value: 'xujiahui', label: '徐家汇' },
          { value: 'huashan', label: '华山' }
        ]
      }
    ]
  }
]

// 开始编辑
const startEditing = () => {
  // 备份原始数据
  originalFormData = JSON.parse(JSON.stringify(profileForm))
  isEditing.value = true
}

// 取消编辑
const cancelEditing = () => {
  if (originalFormData) {
    // 恢复原始数据
    Object.assign(profileForm, originalFormData)
  }
  isEditing.value = false
}

// 保存修改
const handleSave = async () => {
  // 表单验证
  try {
    await profileFormRef.value.validate()
  } catch (error) {
    return
  }
  
  saving.value = true
  try {
    // 模拟保存请求
    // 实际项目中应调用 userAPI.updateProfile(profileForm)
    await new Promise(resolve => setTimeout(resolve, 1500))
    
    ElMessage.success('个人信息保存成功')
    isEditing.value = false
  } catch (error) {
    ElMessage.error('保存失败：' + (error.message || '网络异常，请稍后重试'))
    console.error('保存个人信息失败:', error)
  } finally {
    saving.value = false
  }
}

// 头像上传前处理
const beforeUploadAvatar = (file) => {
  const isLt2M = file.size / 1024 / 1024 < 2
  if (!isLt2M) {
    ElMessage.error('上传头像图片大小不能超过 2MB!')
    return false
  }
  
  // 模拟上传成功
  const reader = new FileReader()
  reader.onload = (e) => {
    profileForm.avatar = e.target.result
  }
  reader.readAsDataURL(file)
  
  return false // 阻止默认上传行为
}

// 跳转到修改手机号页面
const goToModifyPhone = () => {
  ElMessage.info('即将跳转到修改手机号页面')
  // router.push('/user/modify-phone')
}

// 跳转到修改密码页面
const goToModifyPassword = () => {
  ElMessage.info('即将跳转到修改密码页面')
  // router.push('/user/modify-password')
}

// 跳转到设置支付密码页面
const goToSetPayPassword = () => {
  ElMessage.info('即将跳转到设置支付密码页面')
  // router.push('/user/set-pay-password')
}
</script>

<style scoped>
.profile-container {
  background-color: #fff;
}

.profile-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  padding: 20px 0;
  border-bottom: 1px solid $border-color;
  margin-bottom: 20px;
}

.page-title {
  font-size: $font-size-lg;
  font-weight: 500;
  color: $text-color;
  margin: 0;
}

.edit-btn {
  height: 36px;
}

.profile-form {
  padding: 0 20px 20px;
}

/* 头像上传 */
.avatar-uploader {
  display: flex;
  flex-direction: column;
  align-items: flex-start;
}

.avatar-upload {
  border: 1px dashed $border-color;
  border-radius: $border-radius-base;
  width: 120px;
  height: 120px;
  cursor: pointer;
  position: relative;
  overflow: hidden;
  margin-bottom: 10px;
}

.avatar-upload:hover {
  border-color: $primary-color;
}

.avatar {
  width: 100%;
  height: 100%;
  display: block;
  object-fit: cover;
}

.avatar-uploader-icon {
  font-size: 28px;
  color: #8c939d;
  width: 120px;
  height: 120px;
  display: flex;
  align-items: center;
  justify-content: center;
}

.avatar-tip {
  font-size: $font-size-sm;
  color: $text-color-secondary;
  margin: 0;
}

/* 表单区块 */
.form-section {
  margin-bottom: 30px;
}

.section-title {
  font-size: $font-size-base;
  font-weight: 500;
  color: $text-color;
  margin-bottom: 15px;
  padding-left: 10px;
  border-left: 3px solid $primary-color;
}

.profile-form :deep(.el-form-item) {
  margin-bottom: 20px;
}

.modify-link {
  margin-left: 10px;
  cursor: pointer;
}

/* 操作按钮 */
.save-btn,
.cancel-btn {
  margin-right: 10px;
}

/* 响应式设计 */
@media (max-width: 768px) {
  .profile-header {
    flex-direction: column;
    align-items: flex-start;
  }
  
  .edit-btn {
    margin-top: 10px;
  }
  
  .profile-form {
    padding: 0 10px 10px;
  }
  
  .avatar-upload {
    width: 100px;
    height: 100px;
  }
  
  .avatar-uploader-icon {
    width: 100px;
    height: 100px;
  }
}
</style>